package com.bulid.controller;

import com.bulid.pojo.Books;
import com.bulid.service.BookService;
import com.bulid.service.BookServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述：
 */
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //    查询所有的书籍并返回页面
    @RequestMapping("/allBook")
    public String list(Model model) {
        List<Books> list = bookService.queryAllBook();
        // 返回前端
        model.addAttribute("list", list);
        return "allBook";
    }

    // 跳转到添加页面
    @RequestMapping("/toAddBook")
    public String toAddPage() {
        return "addBook";
    }

    // 添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books) {
        System.out.println("addBook=>" + books);
        bookService.addBook(books);
        return "redirect:/book/allBook"; // 重定向到@RequestMapping("/allBook") 请求
    }

    /**
     * 修改页面出 Name 外的值不输出 有可能是 get set的问题
     */
    /**
     * 修改页面
     * @return
     */
    @RequestMapping("/toUpdateBook")
    public String toUpdatePage(int id,Model model) {
        Books books = bookService.queryBookById(id);
        model.addAttribute("QBooks",books);
        return "/updateBook";
    }

    /**
     * 无自动提交事务 提交不成功(不需要事务也可以)
     * @param books
     * @return
     */
    @RequestMapping("/updateBook")
    public String Updatebook(Books books) {
        System.out.println("updateBook=>" + books);
        int i = bookService.updateBook(books);
        if (i > 0){
            System.out.println("添加book成功"+books);
        }
        // 重定向到@RequestMapping("/allBook") 请求
        return "redirect:/book/allBook";
    }
    @RequestMapping("/deleteBook/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id){
        bookService.deleteBookById(id);
        // 重定向到@RequestMapping("/allBook") 请求
        return "redirect:/book/allBook";
    }
    /**
     * 查询书籍
     */
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,Model model){
        Books books = bookService.queryBookByName(queryBookName);
        List<Books> list = new ArrayList<Books>();
        list.add(books);
        if (books == null){
            list = bookService.queryAllBook();
            model.addAttribute("error","未查到");
        }
        model.addAttribute("list", list);
        return "allBook";
    }
}
